// pages/consultionDetail/consultionDetail.js
import { getMyDetail, fillEvaluation } from '../../api/person'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    consultationDetail: null, // 咨询详情
    loading: false,
    id: null, // 订单ID
    
    // 评价相关数据
    showEvaluationModal: false,
    showResultModal: false,
    evaluationScore: 5,
    evaluationContent: '',
    ratingText: '满意',
    isEditing: false, // 是否是编辑模式
    source: 'consultation',
    pageTitle: '咨询详情',
  },
  setPageTitle() {
    const { source } = this.data;
    let title = '';
    
    if (source === 'appointment') {
      title = '预约详情';
    } else {
      title = '咨询详情';
    }
    
    // 设置 top-bar 组件标题
    this.setData({
      pageTitle: title
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('接收到的参数:', options);
    
    if (options && options.id) {
      this.setData({
        id: options.id,
        source: options.source || 'consultation' // 默认为咨询详情
      });
      this.getConsultationDetail(options.id);
      this.setPageTitle();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 获取咨询详情
  getConsultationDetail(id) {
    this.setData({ loading: true });
    
    const studentInfo = wx.getStorageSync('studentInfo');
    const studentId = studentInfo ? studentInfo.id : null;
    
    getMyDetail(id, studentId).then(res => {
      console.log('咨询详情:', res);
      
      // 处理数据，添加星期信息
      const processedData = this.processConsultationData(res);
      
      this.setData({
        consultationDetail: processedData,
        loading: false
      });
    }).catch(err => {
      console.error('获取咨询详情失败:', err);
      wx.showToast({
        title: '获取详情失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    });
  },

  // 处理咨询数据
  processConsultationData(data) {
    if (!data) return data;
    
    // 添加星期信息
    if (data.consultDate) {
      data.weekDay = this.getWeekDay(data.consultDate);
    }
    
    // 确保咨询类型文本存在
    if (!data.consultTypeText) {
      data.consultTypeText = this.getConsultTypeText(data.consultType);
    }
    
    return data;
  },

  getWeekDay(dateString) {
    const match = dateString.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
    
    if (!match) {
      return '日期格式错误';
    }
    
    const year = parseInt(match[1]);
    const month = parseInt(match[2]);
    const day = parseInt(match[3]);
    
    const date = new Date(year, month - 1, day);
    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    
    return weekDays[date.getDay()];
  },
  
  // 获取咨询类型文本
  getConsultTypeText(consultType) {
    const typeMap = {
      1: '电话咨询',
      0: '线下咨询',
      2: '网络咨询',
      3: '在线聊天'
    };
    return typeMap[consultType] || '其他咨询';
  },

  // 获取评分文本
  getRatingText(score) {
    const ratingTexts = {
      1: '不满意',
      2: '不满意',
      3: '一般',
      4: '一般',
      5: '满意'
    };
    return ratingTexts[score] || '满意';
  },

  // 填写反馈 - 打开模态框
  onFeedback() {
    this.setData({
      showEvaluationModal: true,
      evaluationScore: 5,
      evaluationContent: '',
      ratingText: '满意',
      isEditing: false
    });
  },

  // 编辑反馈
  onEditFeedback() {
    const detail = this.data.consultationDetail;
    this.setData({
      showEvaluationModal: true,
      evaluationScore: detail.evaluationScore || 5,
      evaluationContent: detail.evaluationContent || '',
      ratingText: this.getRatingText(detail.evaluationScore || 5),
      isEditing: true
    });
  },

  // 关闭评价模态框
  onCloseEvaluationModal() {
    this.setData({
      showEvaluationModal: false
    });
  },

  // 关闭结果模态框
  onCloseResultModal() {
    this.setData({
      showResultModal: false
    });
  },

  // Rate 组件评分变化
  onRateChange(e) {
    const score = e.detail;
    this.setData({
      evaluationScore: score,
      ratingText: this.getRatingText(score)
    });
  },

  // 反馈输入
  onFeedbackInput(e) {
    this.setData({
      evaluationContent: e.detail.value
    });
  },

  // 提交评价
  onSubmitEvaluation() {
    const { evaluationScore, evaluationContent, id, isEditing } = this.data;
    
    // 准备提交数据
    const evaluationData = {
      id: id,
      evaluationContent: evaluationContent || '',
      evaluationScore: evaluationScore
    };

    console.log('提交评价数据:', evaluationData);

    // 显示加载中
    wx.showLoading({
      title: '提交中...',
    });

    fillEvaluation(evaluationData).then(res => {
      wx.hideLoading();
      console.log('评价提交成功', res);
      
      if (isEditing) {
        // 编辑模式：直接关闭模态框
        this.setData({
          showEvaluationModal: false
        });
        wx.showToast({
          title: '反馈更新成功',
          icon: 'success'
        });
      } else {
        // 新建模式：显示结果模态框
        this.setData({
          showEvaluationModal: false,
          showResultModal: true
        });
      }
      
      // 重新加载详情数据
      this.getConsultationDetail(id);
      
    }).catch(err => {
      wx.hideLoading();
      console.error('评价提交失败', err);
      wx.showToast({
        title: '评价提交失败，请重试',
        icon: 'none'
      });
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if (this.data.id) {
      this.getConsultationDetail(this.data.id);
    }
    wx.stopPullDownRefresh();
  }
})